package com.huashizhaoxi.lionapp.controller;

import com.huashizhaoxi.lionapp.entity.FruitOrderChild;
import com.huashizhaoxi.lionapp.entity.FruitOrderMain;
import com.huashizhaoxi.lionapp.entity.Result;
import com.huashizhaoxi.lionapp.entity.User;
import com.huashizhaoxi.lionapp.entity.complexType.FruitOrderComplexType;
import com.huashizhaoxi.lionapp.entity.requestType.FruitOrderRequestType;
import com.huashizhaoxi.lionapp.entity.responseType.FruitOrderResponseType;
import com.huashizhaoxi.lionapp.service.FruitOrderService;
import com.huashizhaoxi.lionapp.service.UserService;
import com.huashizhaoxi.lionapp.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fruitOrder")
@EnableTransactionManagement
public class FruitOrderController {

    @Autowired
    private FruitOrderService fruitOrderService;

    @Autowired
    private UserService userService;

    Logger log = LoggerFactory.getLogger(FruitOrderController.class);
    private JwtUtils jwtUtils;




    // 商家需要接单的订单
    @GetMapping("/getFruitOrder/valid")
    public Result getValidFruitOrder(@RequestHeader("mytoken") String token){
        Map<String,Object> map1 = jwtUtils.parseJwt(token);
        if(map1 == null) {
            return Result.error("token无效");
        }
        User user = userService.getUserByOpenId((String) map1.get("open_id"));
        if(user.getRole() != 3&&user.getRole() != 2){
            return Result.error("权限不足");
        }
        List<FruitOrderMain> fruitOrderMainList = fruitOrderService.getValidFruitOrder();
        if(fruitOrderMainList != null){
            List<FruitOrderResponseType> fruitOrderResponseTypeList = new ArrayList<>();
            for(FruitOrderMain fruitOrderMain : fruitOrderMainList){
                FruitOrderResponseType fruitOrderResponseType = new FruitOrderResponseType();
                fruitOrderResponseType.setFruitOrderMain(fruitOrderMain);
                fruitOrderResponseType.setFruitOrderComplexTypeList(fruitOrderService.getFruitOrderComplexTypeList(fruitOrderMain.getId()));
                fruitOrderResponseTypeList.add(fruitOrderResponseType);
            }
            return Result.success("获取订单成功",fruitOrderResponseTypeList);
        }else{
            return Result.error("获取订单失败");
        }
    }


}
